/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: BaseMarketFragmentPresent.java
 *   @Date: 1/14/19 8:05 PM
 *   @Author: chenjun
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.app.market.presenter;

import android.os.Bundle;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import io.bhex.app.base.AppUI;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BaseFragmentPresenter;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.QuoteBean;
import io.bhex.sdk.quote.bean.QuoteTokensBean;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.quote.bean.TickerListBean;
import io.bhex.sdk.socket.NetWorkObserver;

public abstract class BaseMarketFragmentPresenter<V extends BaseMarketFragmentPresenter.BaseMarketFragmentUI> extends BaseFragmentPresenter<V> {

    //创建tab 数据Map
    LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap = new LinkedHashMap<>();    //key is quote tokenId
    List<CoinPairBean> mCoinPairList;
    private boolean isVisible;

    public interface BaseMarketFragmentUI extends AppUI {

        void showTabOfQuoteTokens(LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap);

        String getCurrentTab();

        void notifyDataChange(QuoteTokensBean.TokenItem tokenItem);

        boolean isSelected();

    }

    @Override
    public void onUIReady(BaseCoreActivity activity, V ui) {
        super.onUIReady(activity, ui);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SymbolDataManager.GetInstance().setLoginChangeObserver(new SymbolDataManager.LoginstatusChange() {
            @Override
            public void onFavriateChange() {
                getCoinPairList();
            }
        });
        //getCoinPairList();

    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(getUI().isSelected() && isVisible) {
            getCoinPairList();
        }
//        changePage(getUI().getCurrentTabId());
    }

    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        isVisible = visible;
        DebugLog.e("FragmentXX","BASE MarketFragment isVisible = " + isVisible +"  "+ this.toString());
        if (isVisible  && getUI().isSelected()) {
            getRealTimeData();
        }
    }

    /*    @Override
    public void onPause() {
        super.onPause();
//        NetWorkApiManager.getQuoteInstance().UnSubRequestNetWork("realtimes");
        //QuoteApi.UnSubTickers();
    }

    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        if (visible && getUI().isSelected()) {
//            changePage(getUI().getCurrentTabId());
            if(tabMap == null || tabMap.size() == 0)
                getCoinPairList();
            else
                getRealTimeData();
        }else{
            //QuoteApi.UnSubTickers();
        }

    }*/

    /**
     * 获取报价Token集合
     */
    abstract protected void getCoinPairList();

    /**
     * 创建tab数据集
     *
     * @param response
     */
    abstract protected LinkedHashMap<String, QuoteTokensBean.TokenItem> createTabMap(List<QuoteTokensBean.TokenItem> response) ;



    /**
     * 拼接行情参数【全部币对ALL】
     *
     * @return
     */
    protected String getSymbolsListStr() {
        StringBuffer stringBuffer = new StringBuffer();
        for (String key : tabMap.keySet()) {
            if (!key.equals(AppData.KEY_FAVORITE)) {//刷出自选,因为其他的列表已经包括
                QuoteTokensBean.TokenItem tokenItem = tabMap.get(key);
                if (tokenItem != null) {
                    HashMap<String, CoinPairBean> coinPairMap = tokenItem.getCoinPairMap();
                    if (coinPairMap != null) {
                        if (!coinPairMap.isEmpty()) {
                            for (String keyOfCoin : coinPairMap.keySet()) {
                                CoinPairBean coinPairBean = coinPairMap.get(keyOfCoin);
                                if (coinPairBean != null) {
                                    String symbol = coinPairBean.getExchangeId() + "." +coinPairBean.getSymbolId();
                                    if (stringBuffer.toString().length() > 0) {
                                        stringBuffer.append("," + symbol);
                                    } else {
                                        stringBuffer.append(symbol);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return stringBuffer.toString();
    }

    public void getRealTimeData(){
        if(tabMap == null || tabMap.size() == 0)
            getCoinPairList();
        else {
            String symbolsListStr = getSymbolsListStr();
            QuoteApi.SubTickers(symbolsListStr, new NetWorkObserver<TickerListBean>() {
                @Override
                public void onShowUI(TickerListBean response) {
                    if (getUI() == null || !getUI().isAlive() || response == null)
                        return;

                    List<TickerBean> datas = response.getData();
                    if (datas != null) {
                        for (TickerBean data : datas) {
                            handleSocketMarketList(data);
                        }
                    }
                }

                @Override
                public void onError(String error) {
                }
            });
        }
    }

    private void handleSocketMarketList(TickerBean tickerBean) {
        String currentTab = getUI().getCurrentTab();
        QuoteTokensBean.TokenItem currentTokenItem = tabMap.get(currentTab);

        for (String key : tabMap.keySet()) {
            QuoteTokensBean.TokenItem tokenItem = tabMap.get(key);
            //每个tab下的列表实体
            if (tokenItem != null) {
                HashMap<String, CoinPairBean> coinPairMap = tokenItem.getCoinPairMap();
                if (coinPairMap != null) {
                    String tickerSymbolId = tickerBean.getS();
                    if (coinPairMap.containsKey(tickerSymbolId)) {
                        CoinPairBean coinPairBean = coinPairMap.get(tickerSymbolId);
                        if (coinPairBean != null) {
                            String symbol = coinPairBean.getSymbolId();
                            if (symbol.equals(tickerSymbolId)) {
                                coinPairBean.setTicker(tickerBean);
                                if(currentTokenItem == tokenItem)
                                    notifyCoinPairListDataChange(tabMap);
                            }
                        }
                    }

//                    for (String coinKey : coinPairMap.keySet()) {
//                        CoinPairBean coinPairBean = coinPairMap.get(coinKey);
//                        String symbol = coinPairBean.getSymbolId();
//                        String symbolTicker = tickerBean.getS();
//                        if (symbol.equals(symbolTicker)) {
//                            QuoteBean quote = coinPairBean.getQuote();
//                            if (quote == null) {
//                                quote = new QuoteBean();
//                                coinPairBean.setQuote(quote);
//                            }
//                            quote.setV(tickerBean.getV());
//                            quote.setL(tickerBean.getL());
//                            quote.setH(tickerBean.getH());
//                            quote.setO(tickerBean.getO());
//                            quote.setC(tickerBean.getC());
//                            quote.setT(tickerBean.getT());
//                            if(currentTokenItem == tokenItem)
//                                notifyCoinPairListDataChange(tabMap);
//                        }
//
//                    }

                }

            }
        }
    }

    /**
     * 处理币对列表数据
     *
     * @param listBean
     */
    abstract protected void handCoinPairListData(List<CoinPairBean> listBean);

    /**
     * 提示币对数据更新
     *
     * @param tabMap
     */
    public void notifyCoinPairListDataChange(HashMap<String, QuoteTokensBean.TokenItem> tabMap) {
        String currentTab = getUI().getCurrentTab();
        QuoteTokensBean.TokenItem tokenItem = tabMap.get(currentTab);
        getUI().notifyDataChange(tokenItem);
        /*if (tokenItem != null) {
            EventBus.getDefault().post(tokenItem);
        } else {
            DebugLog.e("MarketList tokenItem is null of " + currentTab);
        }*/
    }

    protected String getSymbolsListStr(List<CoinPairBean> list) {
        StringBuffer stringBuffer = new StringBuffer();
        if (list != null && list.size() > 0) {
            for (CoinPairBean coinPairBean : list) {
                if (coinPairBean != null) {
                    String symbol = coinPairBean.getExchangeId() + "." + coinPairBean.getSymbolId();
                    if (stringBuffer.toString().length() > 0) {
                        stringBuffer.append("," + symbol);
                    } else {
                        stringBuffer.append(symbol);
                    }
                }
            }

        }
        return stringBuffer.toString();
    }

    public void changePage(String tabName) {
        notifyCoinPairListDataChange(tabMap);
    }

}
